package cq.zhcqk.fragment._1_news;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zzhoujay.richtext.RichText;

import org.apache.http.Header;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Map;

import cq.zhcqk.R;
import cq.zhcqk.activity.ShowWebImageActivity;
import cq.zhcqk.adapter.MyExpandableListViewAdapter;
import cq.zhcqk.util.AsyncHttpClientUtils;
import cq.zhcqk.util.Common;
import cq.zhcqk.util.GsonUtil;
import cq.zhcqk.util.JsUtil;
import cq.zhcqk.util.WebViewHeader;
import cq.zhcqk.widget.MyExpandableListView;

//import com.mrw.wzmrecyclerview.Divider.BaseItemDecoration;
//import com.mrw.wzmrecyclerview.HeaderAndFooter.OnItemClickListener;
//import com.mrw.wzmrecyclerview.HeaderAndFooter.OnItemLongClickListener;
//import com.mrw.wzmrecyclerview.LayoutManager.WZMGridLayoutManager;
//import com.mrw.wzmrecyclerview.PullToLoad.OnLoadListener;
//import com.mrw.wzmrecyclerview.PullToLoad.PullToLoadRecyclerView;
//import com.mrw.wzmrecyclerview.PullToRefresh.OnRefreshListener;
//import com.mrw.wzmrecyclerview.SimpleAdapter.SimpleAdapter;
//import com.mrw.wzmrecyclerview.SimpleAdapter.ViewHolder;

/**
 * Created by zhangle on 2017/11/25.
 */
public class _2_GzFragment extends Fragment implements View.OnClickListener{
    private View view;
    private Context context;
    private AsyncHttpClient httpClient;
    private TextView text_test;
    private RichText richText;
    private int page = 1;
    private String type = "2";
    private WebView webTest;
    private MyExpandableListView listView;
    private MyExpandableListViewAdapter myExpandableListViewAdapter;
    private ArrayList<Map<String, Object>> mapData = new ArrayList<>();

    private TextView textWc;
    private TextView textP;
    private TextView textBuss;
    private TextView textJiayou;
    private TextView textBank;
    private TextView textPcs;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if(view==null){
            view = inflater.inflate(R.layout.fagment_gz_1_2, container, false);
            httpClient = AsyncHttpClientUtils.getInstance().getAsyncHttpClient();
            context = getActivity();
            initView();
//            getNes(page,type);
//            initListData();
            getList("");
        }
        ViewGroup parent=(ViewGroup)view.getParent();
        if(parent!=null){
            parent.removeView(view);
        }
        return view;
    }

    private void initView(){
        RichText.initCacheDir(context);
        text_test = (TextView) view.findViewById(R.id.gz_detail);
        webTest = (WebView)view.findViewById(R.id.webTest);
        setWeb();

        WebViewHeader.setHeaderAndLoad(webTest,Common.URL+"/api/tourism/");

        listView = (MyExpandableListView) view.findViewById(R.id.listView);
        listView.setGroupIndicator(null);

        // 监听组点击
        listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener()
        {
            @SuppressLint("NewApi")
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id)
            {
                if (mapData.get(groupPosition).isEmpty())
                {
                    return true;
                }
                return false;
            }
        });
        // 监听每个分组里子控件的点击事件
        listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener()
        {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
            {
//                Toast.makeText(context, "group=" + groupPosition + "---child=" + childPosition + "---" + mapData.get(groupPosition).get(childPosition), Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        textWc = (TextView) view.findViewById(R.id.textWc);
        textP = (TextView) view.findViewById(R.id.textP);
        textBuss = (TextView) view.findViewById(R.id.textBuss);
        textJiayou = (TextView) view.findViewById(R.id.textJiayou);
        textBank = (TextView) view.findViewById(R.id.textBank);
        textPcs = (TextView) view.findViewById(R.id.textPcs);
        textWc.setOnClickListener(this);
        textP.setOnClickListener(this);
        textBuss.setOnClickListener(this);
        textJiayou.setOnClickListener(this);
        textBank.setOnClickListener(this);
        textPcs.setOnClickListener(this);
    }

    public void setWeb(){
        WebSettings settings = webTest.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setBuiltInZoomControls(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setDatabaseEnabled(true);
        settings.setBuiltInZoomControls(false);
        settings.setSupportZoom(false);
        settings.setDisplayZoomControls(false);

        webTest.addJavascriptInterface(new JavascriptInterface(context), "imagelistner");
        if(webTest != null)
        {
            webTest.setWebViewClient(new WebViewClient()
            {
                @Override
                public void onPageFinished(WebView view,String url)
                {
                    JsUtil.addImageClickListner(webTest);
//                    DialogUIUtils.dismiss(buildBean);
                }

                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);
//                    buildBean.show();
                }
            });
        }
    }

    private void getNes(int offset,String type){
        RequestParams params = new RequestParams();
        params.add("limit",Common.PAGE_SIZE);
        params.add("offset",offset+"");
        params.add("type",type);
        httpClient.post(Common.URL+Common.NEWS_LIST,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                ArrayList<Map<String, Object>> listNew = null;
                listNew = (ArrayList<Map<String, Object>>)((Map<String, Object>)map.get("data")).get("rows");
                if(listNew == null || listNew.size()==0){
                    Toast.makeText(context,"没有更多",Toast.LENGTH_SHORT).show();
                }else{
//                    getDetail(StringUtil.stringToInt(listNew.get(0).get("cid")+"")+"");
//                    webTest.loadUrl(Common.URL+"/blog/open/post/"+listNew.get(0).get("cid")+"",null);
                    WebViewHeader.setHeaderAndLoad(webTest,Common.URL+"/api/tourism/");
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("onFailure："+errorResponse);
            }
        });
    }

    private String relaceUrl(String content){
        String info = content.replace("<img src=\"/","<img src=\""+Common.URL+"/");
        System.out.println(info);
        return info;
    }

    private void getDetail(String cid){
        RequestParams params = new RequestParams();
        params.add("cid",cid);
        httpClient.post(Common.URL+Common.NEWS_DETAIL,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                if(map != null && map.size()>0){
                    Map<String, Object> mapData = (Map<String, Object>) map.get("data");
                    if(mapData != null && mapData.size()>0){
                        richText = RichText.from(relaceUrl(mapData.get("content")+"")).into(text_test);
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

    private void getList(String cid){
        RequestParams params = new RequestParams();
        params.add("id",cid);
        httpClient.post(Common.URL+Common.TOURISM,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess：古镇旅游景点:"+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                if(map != null && map.size()>0){
                    mapData = (ArrayList<Map<String, Object>>) map.get("data");
                    if(mapData != null && mapData.size()>0){
                        myExpandableListViewAdapter = new MyExpandableListViewAdapter(context,mapData);
                        listView.setAdapter(myExpandableListViewAdapter);
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("errorResponse：古镇旅游景点:"+errorResponse);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                System.out.println("responseString：古镇旅游景点:"+responseString);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

    @Override
    public void onClick(View v) {
        String address;
        String uristr;
        Uri uri;
        Intent intent;
        switch (v.getId()){
            case R.id.textWc:
                address = "address="+ "磁器口公厕";
                uristr = "http://api.map.baidu.com/geocoder?" + address
                        + "&output=html&src=yhc";
                uri = Uri.parse(uristr);
                intent = new Intent(Intent.ACTION_VIEW, uri);
                context.startActivity(intent);
                break;
            case R.id.textP:
                address = "address="+ "磁器口停车场";
                uristr = "http://api.map.baidu.com/geocoder?" + address
                        + "&output=html&src=yhc";
                uri = Uri.parse(uristr);
                intent = new Intent(Intent.ACTION_VIEW, uri);
                context.startActivity(intent);
                break;
            case R.id.textBuss:
                address = "address="+ "磁器口公交站";
                uristr = "http://api.map.baidu.com/geocoder?" + address
                        + "&output=html&src=yhc";
                uri = Uri.parse(uristr);
                intent = new Intent(Intent.ACTION_VIEW, uri);
                context.startActivity(intent);
                break;
            case R.id.textJiayou:
                address = "address="+ "磁器口附近加油站";
                uristr = "http://api.map.baidu.com/geocoder?" + address
                        + "&output=html&src=yhc";
                uri = Uri.parse(uristr);
                intent = new Intent(Intent.ACTION_VIEW, uri);
                context.startActivity(intent);
                break;
            case R.id.textPcs:
                address = "address="+ "磁器口附近派出所";
                uristr = "http://api.map.baidu.com/geocoder?" + address
                        + "&output=html&src=yhc";
                uri = Uri.parse(uristr);
                intent = new Intent(Intent.ACTION_VIEW, uri);
                context.startActivity(intent);
                break;
            case R.id.textBank:
                address = "address="+ "磁器口附近银行";
                uristr = "http://api.map.baidu.com/geocoder?" + address
                        + "&output=html&src=yhc";
                uri = Uri.parse(uristr);
                intent = new Intent(Intent.ACTION_VIEW, uri);
                context.startActivity(intent);
                break;
        }
    }

    public class JavascriptInterface {

        private Context context;

        public JavascriptInterface(Context context) {
            this.context = context;
        }
        @android.webkit.JavascriptInterface
        public void openImage(String img) {
            System.out.println(img);

            Intent intent = new Intent();
            intent.putExtra("image", img);
            intent.setClass(context, ShowWebImageActivity.class);
            context.startActivity(intent);
            System.out.println(img);
        }
    }
}
